import { fetchEventSource, EventSourceMessage,FetchEventSourceInit } from '@microsoft/fetch-event-source'; // 导入类型
import { isHeaders } from './index';

// 定义 start 方法的参数类型
interface StreamControllerOptions extends FetchEventSourceInit  {
  url: string;
  data: unknown; // 可以是任意 JSON 序列化类型
}
class StreamController {
  private abortController: AbortController | null = null;
  private isStreaming: boolean = false;

  // 启动流式请求（返回Promise以便链式调用）
  async start({ url, data, onmessage, onerror }: StreamControllerOptions): Promise<void> {
    // 终止已有连接
    this.abort();

    // 初始化控制器
    this.abortController = new AbortController();
    this.isStreaming = true;

    try {
      const headers = isHeaders(); // 假设 isHeaders 返回 HeadersInit 类型
      
      await fetchEventSource(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(headers as unknown as Record<string, string>) // 类型断言为键值对
        },
        body: JSON.stringify(data),
        signal: this.abortController.signal,
        onmessage: (event: EventSourceMessage) => {
          if (onmessage) {
            console.log('onMessage:' + event.data);
            
            onmessage(event);
          }
        },
        onerror: (err:any) => {
          // 主动中断不触发错误
          if (err instanceof Error && err.name !== 'AbortError') {
            if (onerror) {
              console.log('onError:' + err);

              onerror(err);
            }
          }
          throw err; // 必须抛出以终止
        }
      });
    } catch (err: unknown) {
      // 确保在错误时清理资源
      if (this.abortController) {
        this.abortController.abort();
        this.abortController = null;
      }
      
      // 只传播非主动中断的错误
      if (err instanceof Error && err.name !== 'AbortError') {
        throw err;
      }
    } finally {
      this.isStreaming = false;
    }
  }

  // 终止连接（静默无提示）
  abort(): void {
    if (this.abortController) {
      this.abortController.abort();
      this.abortController = null;
    }
    this.isStreaming = false;
  }

  // 获取当前状态
  get status(): 'active' | 'inactive' {
    return this.isStreaming ? 'active' : 'inactive';
  }
}

export default new StreamController();